<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head th:include="views/CommonJSAndCss.html">
    <title>发起投票</title>
    <!--默认拼接前缀路径,开头请勿再添加斜杠,防止部署运行报错！-->
</head>
<body>
<div class="container">
    <form class="ui form">
        <table class="table table-bordered  ">
            <caption style="color: #2bbbff;font-size: 2em;text-align: center;margin: auto"> 《发起投票的活动》</caption>
            <tr>
                <td class="active text-center"><!--上传头像-->
                    <label th:for="activeName" style="text-align: center;">
                        活动名称
                    </label>
                </td>
                <td class="success"><input type="text" class="form-control" id="activeName" placeholder="活动名称"></td>
                <td class="warning text-center">
                    <label>
                        截止时间
                    </label>
                </td>
                <td class="info" id="errorMsg1">
                    <div class="input-group">
                        <input style="height: 40px" type="text" class="form-control form_datetime" id="time" name="time"
                               placeholder="请选择时间">
                        <span class="input-group-addon" id="basic-addon2"><span class="glyphicon glyphicon-time"
                                                                                aria-hidden="true"></span></span>
                    </div>
                </td>
            </tr>
            <tr>
                <td class="success text-center"><!--上传头像-->
                    <label th:for="activeName" style="text-align: center;">
                        （选填）上传LOGO
                    </label>
                </td>
                <td class="danger"><input name="file" multiple="multiple" th:multiple="multiple"
                                          type="file" id="fileyes"
                                          data-show-caption="true"/></td>
                <td class="info text-center">
                    <label>
                        活动描述
                    </label>
                </td>
                <td class="active" id="errorMsg">
                    <textarea class="form-control" rows="14" id="activityDesc"
                              placeholder="文本描述：禁止输入特殊字符！！"> </textarea>

                </td>
            </tr>
            <tr>
                <td class="success text-center">
                    <label>
                        （选填）设置活动密码：
                    </label>
                </td>
                <td class="danger">
                    <input type="password" class="form-control" id="Activity_PWD1" placeholder="设置活动密码">
                </td>
                <td class="success">
                    <label>
                        （选填）再次输入活动密码：
                    </label>
                </td>
                <td class="warning text-center">
                    <input type="password" class="form-control" id="Activity_PWD2" placeholder="再次输入活动密码">
                </td>
            </tr>
            <tr>
                <td class="warning text-center">
                    <label>
                        是否开启加权投票
                    </label>
                </td>
                <td class="success">
                    <select class="selectpicker" id="isOpen">
                        <option value="1">是</option>
                        <option value="0">否</option>
                    </select>
                </td>
                <td class="warning text-center">
                    <label>
                        登录名：
                    </label>
                    <input type="text" class="form-control" id="This_UserName" placeholder=""
                           th:value="${#authentication.name}" readonly="readonly">
                </td>
                <td class="danger text-center">
                    <label>
                        用户编号：
                    </label>
                    <input type="text" class="form-control" id="This_UserID" placeholder="">
                </td>
            </tr>
        </table>
        <table class="table table-hover" id="table_items">
            <caption>设置被投对象</caption>
            <tbody class="t1">
            <tr>
                <td th:for="activeItemName">目标名称（必填）</td>
                <td><input type="text" class="form-control" id="activeItemName" placeholder="目标名称" name="itemName"></td>
            </tr>
            <tr>
                <td th:for="exampleInputFile">目标形象（可选）</td>
                <td>
                    <table class="table">
                        <tr>
                            <td class="success"><img id="imag_test1" class="img-circle"
                                                     th:src="@{../images/momo/head.jpg}"
                                                     width="50px" height="50px"></td>
                            <td class="info"><input type="file" name="file" accept="image/*" id="itemSendImage1"></td>
                            <td class="danger"><input type="button" value="上传" class="btn btn-success"
                                                      th:onclick="doUpload(1)"></td>
                        </tr>
                    </table>
                    <!--<input type="file" name="exampleInputFile"  id="exampleInputFile">
                    <input type="button" onclick="postData(1);" value="上传">--></td>
            </tr>
            <tr>
                <td th:for="activeItemDesc">目标描述（可选）</td>
                <td><textarea class="form-control" rows="3" placeholder="文本描述：禁止输入特殊字符！！" name="itemDesc"></textarea>
                </td>
            </tr>
            </tbody>

        </table>
        <div class="form-group" style="text-align: right" id="fuhao">
            <img id="jiaHao" th:src="@{/images/index/jiahoa.jpg}" class="img-circle" style="width: 80px;height: 80px">
            <img id="jianHao" th:src="@{/images/index/jianhao.jpg}" class="img-circle" style="width: 50px;height: 50px">
        </div>
        <div class="form-group">
            <div class="col-sm-offset-4 col-sm-4" style="text-align: center">
                <button type="button" class="btn btn-primary" th:onclick="submitThisForm()">立即发起</button>
                <button type="button" class="btn btn-primary" th:onclick="onResetForm()">重置</button>
                <button type="button" class="btn btn-primary">取消</button>
            </div>
        </div>

    </form>
</div>
<script th:inline="javascript">
    var contentPath = [[${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort()  + #request.getContextPath() + '/'}]];
    /*获取用户登录ID*/
    let This_User_ID = [[${#authentication.principal.id}]];
    //提示框初始化
    //消息框初始化设置
    toastr.options = {
        closeButton: false,    // 是否显示关闭按钮，（提示框右上角关闭按钮）
        debug: false,   // 是否使用deBug模式
        progressBar: true, // 是否显示进度条，（设置关闭的超时时间进度条）
        positionClass: "toast-top-center", // 设置提示款显示的位置
        onclick: null, // 点击消息框自定义事件
        showDuration: "300", // 显示动画的时间
        hideDuration: "1000", // 消失的动画时间
        timeOut: "2000", // 自动关闭超时时间
        extendedTimeOut: "1000", // 加长展示时间
        showEasing: "swing", // 显示时的动画缓冲方式
        hideEasing: "linear", // 消失时的动画缓冲方式
        showMethod: "fadeIn", // 显示时的动画方式
        hideMethod: "fadeOut" // 消失时的动画方式
    };
    let count = 1;//计数的
    $(function (ev) {
        //获取当前时间
        let now_date = new Date();
        /*Bootstrap时间*/
        $('.form_datetime').datetimepicker({
            /* minView: "month",  *///选择日期后，不会再跳转去选择时分秒
            language: 'zh-CN',
            dateFormat: 'yyyy-mm-dd',//日期显示格式
            timeFormat: 'HH:mm:ss',//时间显示格式
            todayBtn: 1,//当前时间按钮显示
            autoclose: 1,
            minView: 0,  //0表示可以选择小时、分钟   1只可以选择小时
            minuteStep: 1,//分钟间隔1分钟
            startDate: now_date,//必须大于当前时间
        });
        //文件上传初始化
        initFileInput("fileyes");
        //下拉框初始化
        $('.my-select').selectpicker();
        /*添加按钮*/
        //给添加聚焦手抓形象
        $('#jiaHao').hover(function () {
            $(this).css("cursor", "pointer");
        });
        $('#jianHao').hover(function () {
            $(this).css("cursor", "pointer");
        });
        var isEyes = false;
        //点击加号事件
        $('#jiaHao').click(function (ev) {
            count++;
            $('#table_items').append(`<tbody class="t1">
                    <tr>${count}<td></td>
                    <td>第个${count}选项</td></tr>
                <tr>
                <td th:for="activeItemName">目标名称（必填）</td>
                <td><input type="text" class="form-control" id="activeItemName" placeholder="目标名称" name="itemName"></td>
            </tr>
            <tr>
                <td th:for="exampleInputFile">目标形象（可选）</td>
                <td> <table class="table">
                        <tr>
                            <td class="success"><img id="imag_test${count}" class="img-circle" src="../images/momo/head01.jpg"
                                     width="50px" height="50px"></td>
                            <td class="info"><input type="file" name="file" accept="image/*" id="itemSendImage${count}"></td>
                            <td class="danger"><input type="button" value="上传" class="btn btn-success" onclick="doUpload(${count})"></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td th:for="activeItemDesc">目标描述（可选）</td>
                <td>   <textarea class="form-control" rows="3" placeholder="文本描述：禁止输入特殊字符！！" name="itemDesc"></textarea></td>
            </tr>  </tbody>`)


        });
        /*移出选项*/
        $('#jianHao').click(function (ev) {
            count--;
            if (count >= 1) {
                $("tbody[class=t1]:last").remove();
            } else {
                count = 1;
            }

        });
        let getByIDURl = "student/getUserInfoId";
        /*初始化获取用户ID*/
        $.ajax({
            //请求方式
            type: "get",
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            url: contentPath + getByIDURl,
            //数据，json字符串
            data: {loginId: This_User_ID},
            traditional: true,
            //请求成功
            success: function (result) {
                if (result.code == 200) {
                    $("#This_UserID").attr("readonly", "false");
                    $("#This_UserID").val(result.data);
                    $("#This_UserID").attr("readonly", "true");
                    console.log(result);
                    console.log(result.data);
                }
            },
            //请求失败，包含具体的错误信息
            error: function (e) {
                toastr.error('请求发送失败！');
                console.log(e.status);
                console.log(e.responseText);
            }
        })
    });
    let This_head_Image = "2020/12/23/12804288-ad38-42eb-9ed1-afcebea997bb.jpg";

    //文件上传bootstrap插件
    function initFileInput(ctrlName) {
        var control = $('#' + ctrlName);
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: contentPath + 'oss/uploadfile', //上传的地址
            allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
            uploadAsync: false, //默认异步上传，这里如果不是异步上传，多个图片一次性提交到后台，只发一次请求，如果为异步上传，每张图片都会发一次请求，多次请求
            showUpload: true, //是否显示上传按钮
            showRemove: true, //显示移除按钮
            showPreview: true, //是否显示预览
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式
            maxFileCount: 3, //允许同时上传的最大文件个数
            enctype: 'multipart/form-data',
            validateInitialCount: true,
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
            layoutTemplates: {
                // actionDelete:'', //去除上传预览的缩略图中的删除图标
                // actionUpload:'',//去除上传预览缩略图中的上传图片；
                // actionZoom:'',   //去除上传预览缩略图详情的图标
                // actionDownload:'' //去除上传预览缩略图中的下载图标
            },
            uploadExtraData: function () {   //向后台传递的附带参数
                var data = {
                    id: "10000",
                    msg: "这里可以添加参数"
                };
                return data;
            }
        }).on('filebatchuploadsuccess', function (event, data, previewId, index) {     //上传中
            //console.log(data);
            console.log('文件正在上传');
        }).on("filebatchuploadsuccess", function (event, data, previewId, index) {    //一个文件上传成功
            var form = data.form, files = data.files, extra = data.extra,
                response = data.response, reader = data.reader;
            //获取响应URL
            let saveUrl = response.data.url;
            //处理URL：截取
            This_head_Image = saveUrl.substring(42);
            console.log(response);//打印出返回的json
            console.log(response.status);//打印出状态
        }).on('filebatchuploaderror', function (event, data, msg) {  //一个文件上传失败
            toastr.error('文件上传失败！', data.status);
            console.log('文件上传失败！' + data.status);
        })
    }

    let activeItemImage = new Array();

    //文件上传
    function doUpload(xwsID) {
        toastr.warning('文件上传中!', '当前网速较慢，请耐心等待一会！！');
        /*上传图片*/
        let formData = new FormData();
        let imageByID = 'itemSendImage' + count;
        let file = document.getElementById(imageByID).files[0];
        formData.append("file", file);
        $.ajax({
            url: contentPath + 'oss/uploadfile',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                let xsltDataUrl = returndata.data.url;
                //https://edu-gt.oss-cn-beijing.aliyuncs.com/2020/12/18/862da37c-12d2-410f-8506-b3ed5a9e7685.png
                let saveUrl = xsltDataUrl.substring(42);
                activeItemImage[xwsID - 1] = saveUrl;
                let demo = "#imag_test" + count;
                $(demo).attr("src", xsltDataUrl);
                console.log(activeItemImage);
                toastr.success('文件上传成功！！');
            },
            error: function (returndata) {
                toastr.error('文件上传失败！！');
            }
        });
    }

    function submitThisForm(ev) {

        //判断输入的密码和再次输入密码一致
        if ($("#Activity_PWD1").val() != $("#Activity_PWD2").val()) {
            toastr.error('两次密码输入不一致！');
            return;
        }
        //获取前一对象：
        // 活动名称
        let activeName = $("#activeName").val();
        //结束时间
        let activeTime = $("#time").val();
        //封装时间
        activeTime = activeTime + ":00";
        /*文件最后上传返回的地址*/
        //活动描述
        let activityDesc = $("#activityDesc").val();
        /*是否开放*/
        let isOpen = $("#isOpen option:selected").val();
        /*登录用户的ID*/
        let UserID = $("#This_UserID").val();
        //图片地址
        let headImage = This_head_Image;
        let activityPassword = "";
        if ($("#Activity_PWD1").val() != "" && $("#Activity_PWD1").val() != null) {
            activityPassword = $("#Activity_PWD1").val()
        }
        let studentActivity = {
            activityName: activeName,
            endTime: activeTime,
            activityDesc: activityDesc,
            isShow: isOpen,
            activityImage: headImage,
            openUserId: UserID,
            activityPassword, activityPassword
        };
        console.log(studentActivity);
        //遍历class
        let list = new Array();
        let t1 = $(".t1");
        jQuery.each(t1, function () {
            let itemName = jQuery(this).find("input[name='itemName']").val();
            let itemDesc = jQuery(this).find("textarea[name='itemDesc']").val();
            let ActivityItem = {
                itemName: itemName,
                itemDesc: itemDesc,
            };
            list.push(ActivityItem);
        });
        //封装数据

        for (let i = 0; i < list.length; i++) {
            //把图片地址封装进去
            if (activeItemImage[i] == undefined) {
                list[i].headImg = "2020/12/18/862da37c-12d2-410f-8506-b3ed5a9e7685.png";
            } else {
                list[i].headImg = activeItemImage[i]
            }
        }
        console.log(list);
        //发送请求
        let this_url = "student-activity/addActivity";
        let sendData = {
            studentActivity: studentActivity, list: list
        };
        console.log(sendData);
        $.ajax({
            //请求方式
            type: "POST",
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            url: contentPath + this_url,
            //数据，json字符串
            data: JSON.stringify(sendData),
            traditional: true,
            //请求成功
            success: function (result) {
                if (result.code == 200) {
                    toastr.success('活动创建成功！！！');
                    setTimeout(function () {
                        window.location.href = contentPath + "";
                    }, 3000);
                } else {
                    toastr.error('活动创建失败！');
                }

            },
            //请求失败，包含具体的错误信息
            error: function (e) {
                toastr.error('请求发送失败！');
                console.log(e.status);
                console.log(e.responseText);
            }
        })
    }

    //重置设置为刷新重新加载页面，保留原始的必要数据不丢失
    function onResetForm(ev) {
        window.location.href = contentPath + "level1/goToVote";
    }
</script>
</body>
</html>